<template>
  <lb-layout
    v-loading="$store.getters.loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
    :paddBottom="5"
  >
    <el-row>
      <!-- <z-tree
        ref="tree"
        v-model="deptList"
        varient="energy"
        node-key="id"
        @handleNodeClick="handleNodeClick"
        class="bg left"
      ></z-tree> -->

      <aps-form
        :config="apsForm.formConfig"
        :model="apsForm.formData"
        :formRef="apsForm.formRef"
        :labelWidth="apsForm.labelWidth"
        ref="form"
      ></aps-form>
      <lb-table
        :column="tableData.column"
        :data="tableData.data"
        pagination
        background
        border
        height="710"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[20, 40, 60, 80]"
        :pager-count="5"
        :current-page.sync="currentPage"
        :total="total"
        :page-size="pageSize"
        @size-change="handleSizeChange"
        @p-current-change="handleCurrentChange"
      >
      </lb-table>
    </el-row>
    <operate :id="id" :visible.sync="show" @close="close"></operate>
  </lb-layout>
</template>

<script>
import { list, del } from "@/api/iot/network";
import { dealElectricity } from "@/utils/index";
import auth from "@/plugins/auth";
import zTree from "@/components/zTree";
import operate from "@/views/resource/network/components/operate";
import CascaderSelect from "@/components/Select/CascaderSelect";

export default {
  name: "network",
  components: {
    operate,
    zTree,
    CascaderSelect,
  },
  data() {
    return {
      //弹窗
      id: "",
      show: false,
      // 部门树选项
      deptList: [],
      deptId: "",
      apsForm: {
        formRef: "form",
        labelWidth: "auto",
        formData: {},
        formConfig: {
          formAttr: {
            inline: true,
            size: "small",
          },
          properties: {
            //这里是渲染查询表单的表头和类型的数据
            name: {
              label: "能耗终端名称:",
              typeName: "el-input",
              clearable: true,
              placeholder: "请输入能耗终端名称",
            },
            sysDeptId: {
              label: "用能单位:",
              typeName: "el-select",
              render: (h) => {
                let that = this;
                let formValue = that.$refs?.form?.getFieldsValue().sysDeptId;
                return (
                  <div>
                    <CascaderSelect
                      value={formValue}
                      values={formValue}
                      varient={"energy"}
                      size={"small"}
                      placeholder={"请选择用能单位"}
                      onInput={that.handlerLiandong}
                      filterable={true}
                    ></CascaderSelect>
                  </div>
                );
              },
            },
          },
          formSoltButton: [
            {
              label: "搜索",
              type: "primary",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-search",
              click: this.handlerSearchDetail,
            },
            {
              label: "重置",
              typeName: "el-button",
              size: "small",
              icon: "el-icon-refresh-left",
              click: this.handleReset,
            },
            {
              label: "新增",
              type: "primary",
              typeName: "el-button",
              display: true,
              plain: true,
              size: "small",
              icon: "el-icon-plus",
              click: () => this.operate(""),
            },
          ],
        },
      },
      tableData: {
        column: [
          {
            prop: "code",
            label: "能耗终端编号",
            showOverflowTooltip: true,
          },
          {
            prop: "name",
            label: "终端名称",
            showOverflowTooltip: true,
          },
          {
            label: "所属用能单位",
            prop: "sysDeptName",
            showOverflowTooltip: true,
          },
          // {
          //   prop: "msg",
          //   label: "上级能耗终端",
          //   showOverflowTooltip: true,
          // },
          {
            prop: "location",
            label: "终端地址",
            showOverflowTooltip: true,
          },
          {
            prop: "smartDeviceNum",
            label: "智能设备数量",
            render: (h, scope) => {
              return (
                <div>
                  <zLink
                    varient="archives"
                    underline={true}
                    type="primary"
                    params={{ id: scope.row.id }}
                  >
                    {scope.row.smartDeviceNum}
                  </zLink>
                </div>
              );
            },
          },
          {
            prop: "area",
            label: "用能面积（m²）",
            width: 150,
            render: (h, params) => {
              let num = dealElectricity(params.row.area);
              return h("div", {}, num);
            },
          },
          {
            prop: "userNum",
            label: "用能人数",
          },
          // {
          //   prop: "personInCharge",
          //   label: "负责人",
          // },
          {
            prop: "createTime",
            label: "设立日期",
            width: 150,
          },
          {
            label: "操作",
            width: "150",
            fixed: "right",
            render: (h, scope) => {
              return (
                <div>
                  {
                    <el-button
                      v-hasPermi={["device:networks:edit"]}
                      type="text"
                      size="small"
                      icon="el-icon-edit"
                      onClick={() => {
                        this.operate(scope.row.id);
                      }}
                    >
                      修改
                    </el-button>
                  }
                  {
                    <el-button
                      v-hasPermi={["device:networks:remove"]}
                      type="text"
                      size="small"
                      icon="el-icon-delete"
                      onClick={() => {
                        this.handleOperDelete(scope.row);
                      }}
                      style="color:red"
                    >
                      删除
                    </el-button>
                  }
                </div>
              );
            },
          },
        ],
        data: [],
      },
      radio: 0,
      currentPage: 1,
      pageSize: 20,
      total: 0,
    };
  },
  mounted() {
    // 添加总会管理员角色判断zjuadmin
    this.judgePermi();
    this.initData();
  },
  methods: {
    handlerLiandong(value) {
      let result;
      if (value && value.length > 0) {
        result = value[value.length - 1];
      } else {
        result = null;
      }
      let sysDeptIdChose = result;
      this.$refs?.form?.setFieldValue("sysDeptId", sysDeptIdChose);
    },
    judgePermi() {
      if (auth.hasPermi("device:networks:add")) {
        this.apsForm.formConfig.formSoltButton[2].display = false;
      }
    },
    operate(id) {
      this.id = id;
      this.show = true;
    },
    close(status) {
      this.show = false;
      setTimeout(() => {
        if (status) this.handlerSearchDetail();
      }, 200);
    },
    //删除
    handleOperDelete(row) {
      let that = this;
      const text = "是否确认删除" + (row?.name ?? "该条数据") + "？";
      this.$modal
        .confirm(text)
        .then(() => {
          that.$store.commit("app/updateApiCount", "add");
          del(row.id)
            .then((res) => {
              that.$store.commit("app/updateApiCount");
              if (res.code === 700) {
                that.$message.warning(res.msg);
                return false;
              }

              that.$message.success("已删除!");
              that.initData();
            })
            .catch((err) => {
              that.$store.commit("app/updateApiCount");
              // this.$message.error("系统错误,请联系管理员!30014");
            });
        })
        .catch(() => {});
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.deptId = data.id;
      this.handlerSearchDetail();
    },
    async initData(currentPage, pageSize, data) {
      let that = this;
      let query = {
        ...data,
      };
      if (currentPage) {
        query.pageNum = currentPage;
      } else {
        query.pageNum = that.currentPage;
      }
      if (pageSize) {
        query.pageSize = pageSize;
      } else {
        query.pageSize = that.pageSize;
      }
      that.$store.commit("app/updateApiCount", "add");
      await list(query)
        .then((res) => {
          that.$store.commit("app/updateApiCount");
          if (res.code === 700) {
            that.$message.warning(res.msg);
            return false;
          }
          that.tableData.data = res.rows;
          that.total = res.total;
        })
        .catch((err) => {
          that.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!300010");
        });
    },
    handlerSearchDetail(val) {
      //val===1 删除操作成功后分页边界值处理
      let currentPage = 1;
      if (val === 1) {
        if (
          this.total === (this.currentPage - 1) * this.pageSize + 1 &&
          this.total !== 0 &&
          this.currentPage > 1
        ) {
          currentPage = this.currentPage - 1;
          this.currentPage = currentPage;
        } else {
          currentPage = this.currentPage;
        }
      } else {
        currentPage = this.currentPage;
      }
      const data = {
        ...this.$refs?.form?.getFieldsValue(),
      };
      console.log(data, "qqcs");
      this.initData(currentPage, this.pageSize, data);
    },
    handleSizeChange(val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.handlerSearchDetail();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.handlerSearchDetail();
    },
    handleReset() {
      //重置
      // this.deptId = "";
      // this.deptList = [];
      // this.$refs.tree.$refs.tree.setCurrentKey(null);
      this.$refs?.form?.resetFields();
      this.handlerSearchDetail();
    },
  },
};
</script>

<style scoped lang="scss">
@import "@/assets/styles/mixin.scss";

::v-deep .flex-row {
  display: flex;

  // .left {
  //   width: 220px;
  //   margin-right: 20px;
  //   max-height: 800px;
  //   overflow: auto;
  //   @include scrollBar2;

  //   .el-tree {
  //     @include scrollBar2;
  //   }
  // }

  .right {
    flex: 1;
    width: 100%;
    height: 100%;
    overflow: auto;
    @include scrollBar2;
  }
}
</style>
